package com.lanbu.chat.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.lanbu.chat.domain.ImProblemLog;
import com.lanbu.chat.domain.dto.*;
import com.lanbu.chat.service.IImFastGptService;
import com.lanbu.chat.service.IImProblemLogService;
import com.lanbu.common.config.FastGptProperties;
import com.lanbu.common.constant.DeptConstants;
import com.lanbu.common.core.controller.BaseController;
import com.lanbu.common.core.domain.AjaxResult;
import com.lanbu.common.core.domain.entity.SysDept;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.utils.SecurityUtils;
import com.lanbu.system.domain.SysKnowledgeBase;
import com.lanbu.system.domain.mongo.MongoOpenApis;
import com.lanbu.system.service.ISysDeptService;
import com.lanbu.system.service.ISysKnowledgeBaseService;
import com.lanbu.system.service.impl.MongoOpenApisService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/fastGpt/dataset")
@RequiredArgsConstructor
public class ImFastGptDatasetController extends BaseController {
    private final RestTemplate restTemplate;

    private final String gptLoginUrl = "http://121.37.224.213:3010/api/support/user/account/loginByPassword";

    private final String gptRequestBody = "{\"username\":\"%s\",\"password\":\"%s\"}";

    private final String domain = "121.37.224.213";

    private final String gptUrl = "http://121.37.224.213:3010/dataset/detail?datasetId=670cf2959c15fb1c8459fa14";

    private final FastGptProperties fastGptProperties;

    private final IImFastGptService iImFastGptService;

    private final MongoOpenApisService mongoOpenApisService;

    private final ISysDeptService deptService;

    private final ISysKnowledgeBaseService sysKnowledgeBaseService;

    @Autowired
    private ObjectMapper objectMapper; // 需要添加Jackson依赖
    @Autowired
    private IImProblemLogService imProblemLogService;

    @GetMapping("/toFastGpt")
    @ResponseBody
    public AjaxResult toFastGpt(HttpServletRequest request, HttpServletResponse servletResponse) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        SysDept dept = user.getDept();
        String ancestors = dept.getAncestors();
        // 如果登录的用户部门不是第一层级，则向上找到第一层级
        List<String> splitByAncestors = StrUtil.split(ancestors, ",");
        if (splitByAncestors.size() > DeptConstants.DEPT_UNION_FAST_GPT_DEEP) {
            String s = splitByAncestors.get(DeptConstants.DEPT_UNION_FAST_GPT_DEEP);
            dept = deptService.selectDeptById(Long.valueOf(s));
        }

        String url = gptLoginUrl;
        String jsonBody = String.format(gptRequestBody, dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR, SecureUtil.sha256(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR));

        // 如果是 admin 则用 root 1234 登录
        if (user.isAdmin()) {
            jsonBody = String.format(gptRequestBody, fastGptProperties.getRootName(), SecureUtil.sha256(fastGptProperties.getRootPwd()));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);


        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        String body = response.getBody();
        FastGptResponse bean = JSONUtil.toBean(body, FastGptResponse.class);
        String token = bean.getData().getToken();


        Cookie cookie = new Cookie("fastgpt_token", token);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60);
        cookie.setHttpOnly(true);
        cookie.setDomain(domain);
        servletResponse.addCookie(cookie);
        return success().put("url", gptUrl);
    }

    @ApiOperation("插入反馈问题和反馈答案")
    @PostMapping("/pushData")
    @Transactional
    public AjaxResult pushData(@RequestBody ImProblemLogDto imProblemLogDto) {
        // todo 分页
        SysUser user = SecurityUtils.getLoginUser().getUser();

        SysDept dept = user.getDept();
        String ancestors = dept.getAncestors();
        // 如果登录的用户部门不是第一层级，则向上找到第一层级
        List<String> splitByAncestors = StrUtil.split(ancestors, ",");
        if (splitByAncestors.size() > DeptConstants.DEPT_UNION_FAST_GPT_DEEP) {
            String s = splitByAncestors.get(DeptConstants.DEPT_UNION_FAST_GPT_DEEP);
            dept = deptService.selectDeptById(Long.valueOf(s));
        }

        String url = gptLoginUrl;
        String jsonBody = String.format(gptRequestBody, dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR, SecureUtil.sha256(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR));

        // 如果是 admin 则用 root 1234 登录
        if (user.isAdmin()) {
            jsonBody = String.format(gptRequestBody, fastGptProperties.getRootName(), SecureUtil.sha256(fastGptProperties.getRootPwd()));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        ImProblemLog imProblemLog = new ImProblemLog();

        imProblemLog.setId(imProblemLogDto.getId());
        imProblemLog.setProblem(imProblemLogDto.getProblem());
        imProblemLog.setAnswer(imProblemLogDto.getAnswer());
        imProblemLogService.updateImProblemLog(imProblemLog);

        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

        ImProblemLog imProblemLog1 = imProblemLogService.selectImProblemLogById(imProblemLogDto.getId());

        MongoOpenApis apis = mongoOpenApisService.findByAppId(imProblemLog1.getFastAppId());


        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        String body = response.getBody();
        FastGptResponse bean = JSONUtil.toBean(body, FastGptResponse.class);
        String token = bean.getData().getToken();
        //        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);


        // 设置请求头
        HttpHeaders headers1 = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);  // 设置请求头的类型为 JSON
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));  // 接受 JSON 响应
        headers1.set("Authorization", "Bearer " + apis.getApiKey());  // 设置 Authorization 头部

        // 创建 HttpEntity，包含 JSON 请求体和请求头
        List<QuestionAnswer> list = new ArrayList<>();
        list.add(new QuestionAnswer(imProblemLogDto.getProblem(), imProblemLogDto.getAnswer()));
        HttpEntity<dataRaw> requestEntity2 = new HttpEntity<>(new dataRaw(imProblemLog1.getCollectionId(), "chunk", list), headers1);

        // 发送 POST 请求
        ResponseEntity<String> response1 = restTemplate.exchange(
                "http://121.37.224.213:3010/api/core/dataset/data/pushData",
                HttpMethod.POST, requestEntity2, String.class);

//        Cookie cookie = new Cookie("fastgpt_token", token);
//        cookie.setPath("/");
//        cookie.setMaxAge(60 * 60);
//        cookie.setHttpOnly(true);
//        cookie.setDomain(domain);
//        servletResponse.addCookie(cookie);

        String body1 = response1.getBody();
        return success(body1);
    }


    @ApiOperation("创建知识库")
    @PostMapping("/create")
    public AjaxResult create(Long id, String datasetId, HttpServletResponse servletResponse) {
        // todo 分页
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        SysKnowledgeBase sysKnowledgeBase = sysKnowledgeBaseService.selectSysKnowledgeBaseByDatasetId(datasetId);

        if (sysKnowledgeBase != null && sysKnowledgeBase.getCollectionId() != null && !"".equals(sysKnowledgeBase.getCollectionId())) {
            ImProblemLog imProblemLog = new ImProblemLog();
            imProblemLog.setId(id);
            imProblemLog.setWhetherCreate(1);
            imProblemLog.setCollectionId(sysKnowledgeBase.getCollectionId());
            imProblemLogService.updateImProblemLog(imProblemLog);
            return success();
        }
        //创建 MultiValueMap 来存储多个数据
        //mongoOpenApisService.findByName()
        ImProblemLog imProblemLog = imProblemLogService.selectImProblemLogById(id);
        if (imProblemLog != null) {
            if (imProblemLog.getWhetherCreate() == 1) {
                return success();
            }
        }
        MongoOpenApis apis = mongoOpenApisService.findByAppId(imProblemLog.getFastAppId());
        // 添加其他内容（如文本、文件等）
        ImProblemLogDtoData imProblemLogDtoData = new ImProblemLogDtoData(datasetId, null, "反馈数据集", "virtual", new Metadata("111"));
        // 设置请求头
        HttpHeaders headers1 = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);  // 设置请求头的类型为 JSON
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));  // 接受 JSON 响应
        headers1.set("Authorization", "Bearer " + apis.getApiKey());  // 设置 Authorization 头部

        // 创建 HttpEntity，包含 JSON 请求体和请求头
        HttpEntity<ImProblemLogDtoData> requestEntity2 = new HttpEntity<>(imProblemLogDtoData, headers1);

        // 发送 POST 请求
        ResponseEntity<String> response1 = restTemplate.exchange(
                "http://121.37.224.213:3010/api/core/dataset/collection/create",
                HttpMethod.POST, requestEntity2, String.class);

        String responseBody = response1.getBody();
        String body = "";
        ResponseDto responseDto = null;
        if (responseBody != null) {
            try {
                responseDto = objectMapper.readValue(responseBody, ResponseDto.class);
                body = responseDto.getData();
            } catch (Exception e) {
                e.printStackTrace(); // 处理解析异常
            }
        }

        imProblemLog.setId(id);
        imProblemLog.setWhetherCreate(1);
        imProblemLog.setCollectionId(body);
        imProblemLogService.updateImProblemLog(imProblemLog);
        sysKnowledgeBaseService.insertSysKnowledgeBase(new SysKnowledgeBase(datasetId, body, new Date()));
        return success(body);
    }
}
